<template>
  <div class="d-paner d-paner-noborder">
    <div class="d-paner-body">
      <div class="d-row">
        <div class="d-form-group d-form-group-flex">
          <div class="d-form-label d-text-right">
            <label class="label-text">选择器:</label>
          </div>
          <div class="d-form-el">
            <input v-model="state.selecter" class="d-form-input" type="text" placeholder="默认全部pre元素" />
          </div>
        </div>
        <div class="d-form-el d-text-right">
          <button @click="handleFormat" class="d-btn d-btn-primary d-actions-item" type="button">格式化</button>
        </div>
      </div>
      <div class="d-row" style="padding-top:16px">
        <div class="d-form-group d-form-group-flex">
          <div class="d-form-label d-text-right">
            <label class="label-text">字符串:</label>
          </div>
          <div class="d-form-el">
            <textarea v-model="state.text" class="d-form-textarea" placeholder="输入格式化字符串"></textarea>
          </div>
        </div>
        <div class="d-form-el d-text-right">
          <button @click="handleJSON" class="d-btn d-btn-primary d-actions-item" type="button">格式化</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { parser } from '@daelui/dogjs/dist/components.js'

export default {
  components: {

  },

  props: {

  },

  data () {
    return {
      state: {
        selecter: '',
        text: ''
      }
    }
  },

  watch: {

  },

  methods: {
    /**
     * @function 格式化
    */
    handleFormat () {
      let selecter = this.state.selecter || 'pre'
      let elements = document.querySelectorAll(selecter) || []
      Array.from(elements).forEach(el => {
        let isTextAll = false
        // 判断内容是否是纯文本
        if (el && el.childNodes) {
          let list = []
          Array.from(el.childNodes).forEach(item => {
            if (String(item.nodeType) === '3') {
              list.push(1)
            }
          })
          isTextAll = list.length && list.length === el.childNodes.length
        }
        // 只有内容全是文本时再格式化
        if (isTextAll) {
          let obj = parser.toObject(el.innerHTML, true)
          if (typeof obj !== 'object') {
            return true
          }
          let innerHTML = JSON.stringify(obj, null, '&emsp;')
          // 非pre元素
          if (!/pre/.test(el.tagName)) {
            let pre = document.createElement('pre')
            pre.innerHTML = innerHTML
            el.innerHTML = ''
            el.appendChild(pre)
          } else {
            el.innerHTML = innerHTML
          }
        }
      })
    },
    /**
     * @function 格式化JSON
    */
    handleJSON () {
      let obj = parser.toObject(this.state.text, true)
      if (typeof obj !== 'object') {
        return true
      }
      this.state.text = JSON.stringify(obj, null, ' ')
    }
  },

  beforeMount () {

  },

  mounted () {

  }
}
</script>

<style lang="less" scoped>

</style>
